// 所有页面都有：引用react、pro-components、antd
import { QuestionCircleOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { history, useModel } from '@umijs/max';
import { Button, Popconfirm } from 'antd';
import React from 'react';
// 所有页面都有：引用公共的模块

// 引用自定义的service
import {
  deleteByIdForDevice,
  selectManyByPageForDevice,
  selectManyParams,
  getOnlineStatesEnum,getControlModesEnum,getRemoteControlsEnum,
} from './device-service';

import { message } from '@/shared/EscapeAntd';
import DeviceEdit from './DeviceEdit';

const DeviceList: React.FC = () => {
  //获得当前的农场id，除了Farm表，几乎所有的一级表，都要添加这个字段
  const { initialState } = useModel('@@initialState');
  const farmId = initialState?.currentFarmId;
  if (farmId === undefined) {
    //message.error('请先选择农场');
    console.log('请先选择农场');
    history.push('/user/login');
  }
  // 第1步：定义ref，今后好操作table
  const tableRef = React.useRef<ActionType>();
  // 第2步：创建刷新List
  const listReload = () => {
    tableRef.current?.reload();
  };

  // 第3步：定义两个变量，用来控制新增和编辑弹出框
  const [editVisible, setEditVisible] = React.useState(false);
  const [editId, setEditId] = React.useState<number>(0);

  // 第4步：定义表格中的编辑、删除链接
  const getOption = (record: Farm.Device) => {
    return [
      <a
        key="edit"
        onClick={() => {
          setEditId(record.deviceId);
          setEditVisible(true);
        }}
      >
        编辑
      </a>,
      <Popconfirm
        key="delete"
        placement="topRight"
        title="确定删除该记录吗?"
        icon={<QuestionCircleOutlined style={{ color: 'red' }} />}
        description={
          <>
            删除的数据不可恢复,请谨慎操作。
            <br />
          </>
        }
        onConfirm={() => {
          deleteByIdForDevice(record.deviceId).then((ren) => {
            if (ren.success) {
              message.success('删除成功');
              listReload();
            }
          });
        }}
      >
        <a>删除</a>
      </Popconfirm>,
    ];
  };

  // 第5步：检索条件与要显示的列
  /*
   让AI生成，然后自己修改一下。
   1: 不想查询的列，就把search设为false
*/
  const columns: ProColumns<Farm.Device>[] = [
      {
      title: '农场ID',
      dataIndex: 'farmId',
      key: 'farmId',
    },
    {
      title: '设备名称',
      dataIndex: 'deviceName',
      key: 'deviceName',
    },
    {
      title: '设备SN',
      dataIndex: 'deviceSn',
      key: 'deviceSn',
    },
    {
      title: '设备型号',
      dataIndex: 'deviceModel',
      key: 'deviceModel',
    },
    {
      title: '设备分类id',
      dataIndex: 'deviceClassId',
      key: 'deviceClassId',
    },
    {
      title: '设备厂商',
      dataIndex: 'manufacturer',
      key: 'manufacturer',
    },
    {
      title: '固件版本',
      dataIndex: 'version',
      key: 'version',
    },
    {
      title: '设备图片',
      dataIndex: 'picture',
      key: 'picture',
    },
    {
      title: '在线状态',
      dataIndex: 'onlineState',
      key: 'onlineState',
      valueType: 'select',
      valueEnum: { ...getOnlineStatesEnum() },
    },
    {
      title: '开关状态',
      dataIndex: 'openState',
      key: 'openState',
    },
    {
      title: '控制方式',
      dataIndex: 'controlMode',
      key: 'controlMode',
      valueType: 'select',
      valueEnum: { ...getControlModesEnum() },
    },
    {
      title: '远程控制',
      dataIndex: 'remoteControl',
      key: 'remoteControl',
      valueType: 'select',
      valueEnum: { ...getRemoteControlsEnum() },
    },
    {
      title: '位置坐标',
      dataIndex: 'coordinates',
      key: 'coordinates',
    },
    {
      title: '备注',
      dataIndex: 'remarks',
      key: 'remarks',
    },

    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      render: (_, record) => getOption(record),
    },
  ];

  // 第6步：定义新增按钮
  const toolBarRender = () => [
    <Button
      type="primary"
      key="primary"
      onClick={() => {
        setEditId(0);
        setEditVisible(true);
      }}
    >
      新建
    </Button>,
  ];

  return (
    <PageContainer>
      <ProTable<Farm.Device, selectManyParams & Farm.SelectByPageParams>
        columns={columns}
        actionRef={tableRef}
        request={async (params, sort, filter) => {
          console.log(sort, filter, params);
          const result = await selectManyByPageForDevice({ ...params, farmId: farmId || -1 });
          return {
            data: result.data.list,
            success: true,
            total: result.data.total,
          };
        }}
        pagination={{
          pageSize: 10,
        }}
        headerTitle="设备表列表"
        rowKey="deviceId"
        toolBarRender={toolBarRender}
      ></ProTable>

      {editVisible && (
        <DeviceEdit
          visible={editVisible}
          id={editId}
          setVisible={setEditVisible}
          listReload={listReload}
        />
      )}
    </PageContainer>
  );
};

export default DeviceList;
